package com.ZeroCarbon.utils;

import cn.hutool.core.io.FileUtil;
import com.ZeroCarbon.exception.FileHandingException;
import com.alibaba.nacos.shaded.com.google.common.net.HttpHeaders;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.UUID;

@RequiredArgsConstructor
@Component
public class FileHandingUtils {

    // 表示本地磁盘文件的存储路径
    private static final String filePath = System.getProperty("user.dir") + "/common/files/";

    //上传文件
    public static String uploadFile(String pathPrefix, MultipartFile file) throws FileHandingException {
        //获取原文件名
        String originalFilename = file.getOriginalFilename();
        //生成UUID前缀加后缀的文件名
        String fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
        //拼接完整的文件存储路径
        String realFilePath = filePath + pathPrefix + "/" + fileName;
        try {
            if (!FileUtil.isDirectory(filePath)) {
                FileUtil.mkdir(filePath);
            }
            FileUtil.writeBytes(file.getBytes(), realFilePath);
        } catch (IOException e) {
            throw new FileHandingException("文件上传失败");
        }
        return realFilePath.replace("\\", "/");
    }

    //获取文件
    public static void getFile(String realFilePath, HttpServletResponse response) throws IOException {
        // 切割
        String[] split = realFilePath.split("/");
        //获取文件名
        String filename = split[split.length - 1];
        // 设置响应头（正确方式）
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + filename);

        // 检查文件存在性
        File file = new File(realFilePath);
        if (!file.exists()) {
            throw new RuntimeException("文件" + realFilePath + "不存在");
        }

        // 使用Files.copy传输文件
        Files.copy(file.toPath(), response.getOutputStream());
    }

    //删除文件
    public static void deleteFile(String fileName) {
        // 创建File对象
        File file = new File(fileName);
        //如果存在相关文件则删除
        if (file.exists()) {
            file.delete();
        }
    }
}
